package com.htjc.uep.center.commons.aop.annotation;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import com.htjc.uep.center.commons.annotation.Decrypt;
import com.htjc.uep.center.commons.bean.BeanContext;
import com.htjc.uep.center.commons.utils.JsonUtil;
import com.htjc.uep.center.commons.utils.KeyUtil;
import com.htjc.uep.center.commons.utils.StringUtil;
import com.htjc.uep.center.model.enums.ErrorStatus;


@Component
@Aspect
public class DecryptAspect implements Ordered{

	private Logger log = LoggerFactory.getLogger(this.getClass());
	/**
	 * 定义切点
	 */
	@Pointcut("execution(public * com.htjc..*.*(..))&&@annotation(decrypt)")
	public void decryptPointcut(Decrypt decrypt){};
	
	@Around("decryptPointcut(decrypt)")
	public Object executeTime(ProceedingJoinPoint joinPoint, Decrypt decrypt) throws Throwable {
		
		StopWatch watch = new StopWatch();
		
		String param = joinPoint.getArgs()[0].toString();
		
		Object returnObj = null;
		
		if (StringUtil.isEmpty()) {
			return JsonUtil.getError(ErrorStatus.ERROR_PARAM);
		}
		try {
			watch.start("encrypt");
			KeyUtil keyUtil = BeanContext.getBean(KeyUtil.class);
			String enParam = keyUtil.decryptByPrivate(param);
			watch.stop();
			
			watch.start("run");
			Object[] obj = new Object[]{enParam}; 
			returnObj = joinPoint.proceed(obj);
			watch.stop();
		} catch (Exception e) {
			log.info("切面异常-方法={}", joinPoint.getTarget().getClass().getSimpleName(), e);
			return JsonUtil.getError(ErrorStatus.ERROR_ENCRYPT);
		}
		log.info(watch.prettyPrint());
		return returnObj;
	}

	@Override
	public int getOrder() {
		// TODO Auto-generated method stub
		return 1;
	}
}
